﻿/*
// Exepack.NET compressor
// http://www.codeplex.com/exepack
//
// Progress form
// Written by Y [21-02-10]
// Copyright (c) 2008-2010 Alexey Yakovlev
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Exepack
{
	/// <summary>
	/// Compression progress report form
	/// </summary>
	public partial class ProgressForm : Form
	{
		public ExeCompressor ExePack { get; private set; }

		IDictionary<string, ListViewItem> ListViewItems { get; set; }

		public ProgressForm(Form parentForm, ExeCompressor exepack)
		{
			InitializeComponent();

			ListViewItems = new Dictionary<string,ListViewItem>();
			SetLocation(parentForm);
			Subscribe(ExePack = exepack);
		}

		void SetLocation(Form parentForm)
		{
			if (parentForm != null && parentForm.Visible)
			{
				Left = parentForm.Left + (parentForm.Width - Width) / 2;
				Top = parentForm.Top + (parentForm.Height - Height) / 2;
			}
		}

		void Subscribe(ExeCompressor exepack)
		{
			exepack.CompressionProgress += CompressionProgress;
			exepack.SavingExecutableProgress += SavingExecutableProgress;
		}

		void Unsubscribe(ExeCompressor exepack)
		{
			exepack.SavingExecutableProgress -= SavingExecutableProgress;
			exepack.CompressionProgress -= CompressionProgress;
		}

		void CompressionProgress(object sender, CompressionProgressEventArgs args)
		{
			OperationLbl.Text = "Compressing: " + args.FileName;
			ProgressBar.Value = args.OverallProgress;
			Application.DoEvents();

			var item = GetOrCreateListViewItem(args.FileName);
			item.SubItems.Clear();
			item.Text = args.FileName;

			var packedSize = args.CompressedSize == null ? "..." : args.CompressedSize.ToString();
			item.SubItems.Add(new ListViewItem.ListViewSubItem(item, args.OriginalSize.ToString()));
			item.SubItems.Add(new ListViewItem.ListViewSubItem(item, packedSize));
			Application.DoEvents();
		}

		void SavingExecutableProgress(object sender, CompressionProgressEventArgs args)
		{
			OperationLbl.Text = "Saving: " + args.FileName;
			ProgressBar.Value = args.OverallProgress;
			Application.DoEvents();
		}

		ListViewItem GetOrCreateListViewItem(string name)
		{
			if (!ListViewItems.ContainsKey(name))
			{
				var item = new ListViewItem();
				ListViewItems[name] = item;
				AsmListView.Items.Add(item);
			}

			return ListViewItems[name];
		}
	}
}
